package dijjer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import dijjer.util.logging.Logger;

/**
 * @author turadg
 */
public class Integrity {

	/**
	 * Look for the checksum of <tt>$URL</tt> at <tt>$URL.md5</tt>, a la
	 * Maven
	 * 
	 * @param url
	 *            URL of which to verify the integrity
	 * @return String MD5 checksum found
	 */
	public static String checksumByDotMd5(URL url) {
		try {
			URL md5sumUrl = new URL(url.toExternalForm() + ".md5");
			HttpURLConnection muc = Misc.openHttpUrlConnection(md5sumUrl);
			muc.connect();
			if (muc.getResponseCode() != HttpURLConnection.HTTP_OK) {
				Logger.info("Got " + muc.getResponseMessage()
						+ " when requesting " + md5sumUrl);
				return null;
			}
			BufferedReader br = new BufferedReader(new InputStreamReader(muc
					.getInputStream()));
			String line = br.readLine();
			String checksum;
			int firstSpace = line.indexOf(' ');
			if (firstSpace > 0)
				checksum = line.substring(0, firstSpace);
			else
				checksum = line;
			return checksum;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return null;
	}

	/**
	 * Look for the checksum in a file <tt>MD5SUM</tt> in the same directory
	 * as the given URL
	 * 
	 * @param url
	 *            URL of which to verify the integrity
	 * @return String MD5 checksum found
	 */
	public static String checksumByMD5SUM(URL url) {
		try {
			// Check for md5sum file
			URL md5sumUrl = new URL(url.toString().substring(0,
					url.toString().lastIndexOf("/"))
					+ "/MD5SUM");
			HttpURLConnection muc = Misc.openHttpUrlConnection(md5sumUrl);
			muc.connect();
			if (muc.getResponseCode() != HttpURLConnection.HTTP_OK) {
				Logger.info("Got " + muc.getResponseMessage()
						+ " when requesting " + md5sumUrl);
				return null;
			}
			String filename = url.toString().substring(
					url.toString().lastIndexOf("/") + 1,
					url.toString().length());
			BufferedReader br = new BufferedReader(new InputStreamReader(muc
					.getInputStream()));
			while (true) {
				String line = br.readLine();
				if (line == null) {
					break;
				}
				if (line.indexOf(" ") == -1) {
					continue;
				}
				String m = line.substring(0, line.indexOf(" "));
				String f = line.substring(line.lastIndexOf(" ") + 1, line
						.length());
				if (f.equalsIgnoreCase(filename)) {
					return m;
				}
			}
			muc.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return null;
	}

}
